<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="900">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-position="top"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="审批流名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入审批流名称" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="应用范围 (默认全公司)" prop="department">
            <el-select
              collapse-tags
              collapse-tags-tooltip
              multiple
              :max-collapse-tags="3"
              style="width: 49%; margin-right: 10px"
              v-model="formData.department"
              placeholder="请选择部门"
            >
              <el-option
                v-for="item in departmentOptions"
                :key="item.id"
                :label="item.nickname"
                :value="item.id"
              />
            </el-select>
            <el-select
              multiple
              collapse-tags
              collapse-tags-tooltip
              :max-collapse-tags="3"
              v-model="formData.user"
              style="width: 49%"
              placeholder="请选择员工"
            >
              <el-option
                v-for="item in userOptions"
                :key="item.id"
                :label="item.nickname"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="审批流程" prop="type" class="column">
            <el-radio v-model="formData.type" :label="1">固定审批流</el-radio>
            <el-form ref="listFormRef" :model="dynamicValidateForm">
              <el-form-item
                v-for="(domain, index) in dynamicValidateForm.domains"
                :key="domain.key"
                :label="'第' + (index - 0 + 1) + '级'"
                :prop="'domains.' + index + '.value'"
                class="noBottom"
                style="display: flex; margin-bottom: 10px; align-items: center"
              >
                <el-row class="items-center">
                  <el-select
                    class="mr-10px"
                    v-model="dynamicValidateForm.domains[index].value"
                    clearable
                  >
                    <el-option label="负责人主管" value="2" />
                    <el-option label="指定用户（任意一人）" value="0" />
                    <el-option label="指定用户（多人会签）" value="1" />
                  </el-select>

                  <el-select
                    v-if="
                      dynamicValidateForm.domains[index].value == '0' ||
                      dynamicValidateForm.domains[index].value == '1'
                    "
                    class="mr-30px"
                    filterable
                    v-model="dynamicValidateForm.domains[index].select"
                    multiple
                    collapse-tags-tooltip
                    clearable
                    collapse-tags
                    popper-class="custom-header"
                    :max-collapse-tags="1"
                  >
                    <el-option
                      v-for="item in cities"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>

                  <el-button
                    v-if="index != 0"
                    @click.prevent="removeDomain(domain)"
                    type="danger"
                    :icon="Minus"
                    circle
                    size="small"
                  />
                </el-row>
              </el-form-item>
              <el-form-item>
                <el-button @click="addDomain" text type="primary">+ 添加审批层级</el-button>
              </el-form-item>
            </el-form>
            <div class="examine-add-des">
              <p
                ><span class="examine-add-required">*</span
                >当选择“负责人主管”审批时。系统仅会通知负责人主管。</p
              >
              <p
                ><span class="examine-add-required">*</span
                >当选择多个“指定用户”审批时。如果指定用户没有权限查看对应的合同，系统会通知其审批，但是他无法查看此数据信息。
              </p>
              <p
                ><span class="examine-add-required">*</span
                >当选择“指定用户（任意一人）”表示指定用户中任意一人审批即可。当选择“指定用户（多人会签）”表示
                指定用户中所有人都要审批。</p
              >
            </div>
            <el-radio v-model="formData.type" :label="2">授权审批人</el-radio>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item
            label="流程说明 （请填写相关注意事项，方便员工在申请时查阅，限制输入200字）"
            prop="illustrate"
          >
            <el-input
              v-model="formData.illustrate"
              :rows="4"
              maxlength="200"
              type="textarea"
              show-word-limit
              resize="none"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import { Minus } from '@element-plus/icons-vue'
import * as ContactApi from '@/api/crm/contact'
import { DICT_TYPE, getBoolDictOptions, getIntDictOptions } from '@/utils/dict'
import * as UserApi from '@/api/system/user'
import * as CustomerApi from '@/api/crm/customer'
import * as AreaApi from '@/api/system/area'
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const departmentList = ref([]) // 部门列表
const formData = ref({
  id: undefined,
  name: undefined, // 审批流名称
  department: undefined, // 应用部门
  user: undefined,
  type: undefined, // 审批方式
  illustrate: undefined, // 流程说明
  list: undefined,
  flow: undefined
})
const formRules = reactive({
  name: [{ required: true, message: '审批流名称不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const listFormRef = ref() // 表单 Ref
const departmentOptions = ref<UserApi.UserVO[]>([]) // 用户列表
const options = [
  {
    value: 'Option1',
    label: 'Option1'
  },
  {
    value: 'Option2',
    label: 'Option2'
  },
  {
    value: 'Option3',
    label: 'Option3'
  },
  {
    value: 'Option4',
    label: 'Option4'
  },
  {
    value: 'Option5',
    label: 'Option5'
  }
]

const dynamicValidateForm = reactive<{
  domains: DomainItem[]
  region: string
}>({
  domains: [
    {
      key: 1,
      value: '',
      select: ''
    }
  ],
  region: ''
})

interface DomainItem {
  key: number
  value: string
}
const cities = [
  {
    value: 'Beijing',
    label: 'Beijing'
  },
  {
    value: 'Shanghai',
    label: 'Shanghai'
  },
  {
    value: 'Nanjing',
    label: 'Nanjing'
  },
  {
    value: 'Chengdu',
    label: 'Chengdu'
  },
  {
    value: 'Shenzhen',
    label: 'Shenzhen'
  },
  {
    value: 'Guangzhou',
    label: 'Guangzhou'
  }
]
/**删除一行 */
const removeDomain = (item: DomainItem) => {
  const index = dynamicValidateForm.domains.indexOf(item)
  if (index !== -1) {
    dynamicValidateForm.domains.splice(index, 1)
  }
}

/** 添加一行 */
const addDomain = () => {
  dynamicValidateForm.domains.push({
    key: Date.now(),
    value: '',
    select: ''
  })
}

/** 打开弹窗 */
const open = async (
  type: string,
  id?: number,
  department?: number,
  businessId?: number,
  businessNameId?: number
) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await ContactApi.getContact(id)
    } finally {
      formLoading.value = false
    }
  } else {
    formData.value.type = 1
  }
  // 获得部门列表
  departmentOptions.value = await UserApi.getSimpleUserList()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as ContactApi.ContactVO
    if (formType.value === 'create') {
      await ContactApi.createContact(data)
      message.success(t('common.createSuccess'))
    } else {
      await ContactApi.updateContact(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    name: undefined,
    department: undefined,
    type: undefined,
    illustrate: undefined
  }
  formRef.value?.resetFields()
}
</script>
<style lang="scss" scoped>
.noBottom {
  ::v-deep(.el-form-item__label) {
    margin-bottom: 0 !important;
  }
}

.column {
  ::v-deep(.el-form-item__content) {
    flex-direction: column;
    align-items: flex-start;
  }
}

.examine-add-des {
  padding: 10px;
  margin: 10px 0;
  font-size: 12px;
  line-height: 23px;
  color: #999;
  background-color: #fffcf0;

  p {
    margin: 0;
  }

  .examine-add-required {
    color: #ff6767;
  }
}
</style>
